package com.sbcb.script.rule;

import groovy.lang.GroovyClassLoader;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class RuleLoader {
    private static List<Rule> rules = new ArrayList<>();
    private static Map<String, Rule> ruleMap = new HashMap<>();

    public List<Rule> getRules() {
        if (rules.size() > 0) {
            return rules;
        }
        rules.addAll(ruleMap.values());
        return rules;
    }

    public void addRule(File file) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
        String sName = file.getAbsolutePath() + file.getName();
        rules.clear();
        Rule rule = ruleMap.get(file.getName());
        if (rule == null) {
            Class clazz = compile(file);
            rule = (Rule) clazz.getDeclaredConstructor().newInstance();
            ruleMap.put(file.getName(), rule);
        }
    }

    private Class compile(File file) throws IOException {
        GroovyClassLoader loader = getGroovyClassLoader();
        Class groovyClass = loader.parseClass(file);
        return groovyClass;
    }

    GroovyClassLoader getGroovyClassLoader() {
        return new GroovyClassLoader();
    }
}
